package com.longrise.android.byjk.plugins.poster.posterdetail;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.longrise.LEAP.Base.Util.StringUtils;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.poster.posterdetail.assist.ImageUtil;
import com.longrise.android.byjk.plugins.poster.posterdetail.assist.QrBitmap;
import com.longrise.common.base.BasePresenter;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.utils.FolderConstants;
import com.longrise.common.utils.PrintLog;

import net.bither.util.NativeUtil;

import java.io.File;



/**
 * Created by godliness on 2017/9/25.
 *  分享详情的 图片 fragment
 */

public class PosterFragPresenter extends BasePresenter<PosterFragView> implements RequestListener<String, GlideDrawable> {

    public static final String TAG = "PosterFragPresenter";
    public static final int LDPI = 640;
    public static final int MDPI = 120;
    public static final int HDPI = 160;
    public static final int XDPI = 240;
    public static final int XXDPI = 320;
    public static final int XXXDPI = 480;

    /***图片保存路径*/
    private File mSaveFile;

    /***当前海报是否加载完成*/
    private boolean mPrepared;
    /***当前Fragment索引*/
    private int mCurrent;

    private String url = "";
    private String imgUrl = "";

    @Override
    protected void init() {

    }

    /**
     * 加载图片
     */
    public void preformLoadImage(String url, int position, ImageView iv) {
        this.mCurrent = position;
        imgUrl = url;
        mView.showLoadingDialog();
        if (!StringUtils.isEmpty(url)) {
            Glide.with(mContext).load(url).centerCrop().placeholder(R.drawable.bg_loading_default).listener(this).into(iv);
        }
    }

    @Override
    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
        mPrepared = false;
        mView.dismissLoadingDialog();
        return false;
    }

    @Override
    public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
        mPrepared = true;
        mView.setCurrentDrawable(resource);
        mView.dismissLoadingDialog();
        return false;
    }


    /**
     * 执行分享任务，返回对象实体
     */
    public class CreateSave {

        public CreateSave(boolean saved, String mSaveFile) {
            this.mSaved = saved;
            this.mSavePath = mSaveFile;
        }

        public boolean mSaved;
        public String mSavePath;

        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder("{");
            sb.append("mSaved=").append(mSaved);
            sb.append(", mSavePath='").append(mSavePath).append('\'');
            sb.append('}');
            return sb.toString();
        }
    }

    /**
     * 执行分享任务
     *
     * @return 返回是否保存成功
     */
    public CreateSave preformShare(Drawable drawable) {
        boolean isSaved = createSaveFile(drawable);
        PrintLog.e(TAG,"isSaved=:"+isSaved);
        PrintLog.e(TAG,"path=:"+mSaveFile.getAbsolutePath());
        return new CreateSave(isSaved, mSaveFile.getAbsolutePath());
    }

    /**
     * 生成保存海报的图片名称
     */
    private String generateImgName() {
        String userid = UserInfor.getInstance().getUserid();
        return userid + System.currentTimeMillis() + "_share.jpeg";
    }

    /**
     * 创建保存路径
     */
    private boolean createSaveFile(Drawable drawable) {
        File createPath = new File(FolderConstants.SHARE_POSTER);
        if (!createPath.exists()) {
            createPath.mkdirs();
        }
        mSaveFile = new File(createPath.getAbsolutePath(), generateImgName());
        //if exists is delete
        if (mSaveFile.exists()) {
            mSaveFile.delete();
        }
        if (drawable == null || !mPrepared) {
            return false;
        }
        return saveToFile(drawable, mSaveFile);
    }

    /**
     * 将文件保存到本地
     */
    private boolean saveToFile(Drawable drawable, File outFile) {
        url = UserInfor.getInstance().getUrl();
        Bitmap drawableBitmap = null;
        Bitmap newBitmap = null;
        Bitmap bitmap = null;
        try {
            //获取二维码
            bitmap = QrBitmap.getInstance().createAndGetQrBitmap(mContext);
            if (bitmap == null) {
                float width = ImageUtil.getImgWidth(mContext);
//                float width = ImageUtil.getDp(mContext, R.dimen.image);
                Bitmap qrBitmap = ImageUtil.generateBitmap(url, AppUtil.dip2px(width), AppUtil.dip2px(width));
//                Bitmap qrBitmap = ImageUtil.create2DQrCode(url, ScreenUnit.dip2px(width), ScreenUnit.dip2px(width));
                PrintLog.e(TAG, " width dp = " + width + " width px = " + AppUtil.dip2px(width));
                Bitmap logoBitmap = UserInfor.getInstance().getBitmap();
                if (logoBitmap == null) {
                    logoBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.default_pic);
                }
                bitmap = ImageUtil.addLogo(qrBitmap, logoBitmap);
            }
            drawableBitmap = ImageUtil.drawableToBitmap(drawable);
            //将图片添加上二维码
            newBitmap = ImageUtil.createWaterMaskRightBottom(mContext, drawableBitmap, bitmap, 10, 10);
            //尺寸固定（750 * 1334）对质量进行压缩，控制在200kb以内
//            ImgCompress.imgQualityCompress(newBitmap, 100, outFile, 200);
            //采用霍夫曼压缩
            NativeUtil.compressBitmap(newBitmap, outFile.getAbsolutePath(), 400, true);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (drawableBitmap != null && !drawableBitmap.isRecycled()) {
                    drawableBitmap.recycle();
                }
                if (newBitmap != null && !newBitmap.isRecycled()) {
                    newBitmap.recycle();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}

